package com.fakeDYChat.common.common.interceptor;

import com.fakeDYChat.common.common.domain.dto.RequestInfo;
import com.fakeDYChat.common.common.exception.HttpErrorEnum;
import com.fakeDYChat.common.common.utils.RequestHolder;
import com.fakeDYChat.common.user.domain.enums.BlackTypeEnum;
import com.fakeDYChat.common.user.service.cache.UserCache;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 用于拦截被拉黑的用户
 *
 * @author Tang
 * @date 2024/1/13 13:42
 **/
@Component
public class UserBlackInterceptor implements HandlerInterceptor {
    private final UserCache userCache;

    public UserBlackInterceptor(UserCache userCache) {
        this.userCache = userCache;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<Integer, Set<String>> blackMap = userCache.getBlackMap();
        RequestInfo requestInfo = RequestHolder.get();
        if (inBlackMap(blackMap.get(BlackTypeEnum.IP.getType()), requestInfo.getIp())) {
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
            return false;
        }
        if (inBlackMap(blackMap.get(BlackTypeEnum.UID.getType()), requestInfo.getUid())) {
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
            return false;
        }
        return true;
    }

    /**
     * 判断该用户是否在黑名单
     * @param blackSet
     * @param target
     * @return boolean
     * @author Tang
     * @date 2024/1/13 15:16
    **/
    private boolean inBlackMap(Set<String> blackSet, Object target) {
        if (Objects.isNull(target) || CollectionUtils.isEmpty(blackSet)) {
            return false;
        }
        return blackSet.contains(target.toString());
    }
}
